<template>
  <div class="material-viewer-page">
    <el-card class="viewer-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <el-button :icon="Back" circle @click="goBack" title="返回课程详情"></el-button>
          <h2 class="chapter-title">{{ currentChapterName || '章节标题加载中...' }}</h2>
        </div>
      </template>

      <div class="materials-container">
        <el-row :gutter="20">
          <el-col :span="18">
            <div class="material-display-area">
              <el-empty v-if="!currentMaterial" description="请选择一个章节或资料，或当前章节暂无资料"></el-empty>
              <div v-else class="material-item">
                <template v-if="currentMaterial.type === 'VIDEO'">
                  <h3>视频资料: {{ currentMaterial.name }}</h3>
                  <video :src="currentMaterial.filePath" controls class="material-video"></video>
                  <el-button type="primary" @click="watchVideo(currentMaterial.materialID)" style="margin-top: 10px;">观看并记录学习进度</el-button>
                  <div class="comments-section">
                    <h3>评论区</h3>
                    <div class="comment-input-area">
                      <el-input
                        v-model="newCommentContent"
                        :placeholder="replyingToUserName ? `回复 ${replyingToUserName}:` : '发表评论...'"
                        type="textarea"
                        :rows="3"
                        clearable
                      ></el-input>
                      <div class="comment-submit-actions">
                        <el-button v-if="replyingToCommentId" type="text" @click="replyingToCommentId = null; replyingToUserName = ''; newCommentContent = '';">取消回复</el-button>
                        <el-button type="primary" @click="submitComment">提交评论</el-button>
                      </div>
                    </div>

                    <el-divider v-if="comments.length > 0">评论列表</el-divider>

                    <div v-if="comments.length > 0" class="comment-list-container">
                      <CommentItem
                        v-for="comment in comments"
                        :key="comment.commentID"
                        :comment="comment"
                        @reply="handleReply"
                      />
                    </div>
                    <el-empty v-else description="暂无评论"></el-empty>
                  </div>
                </template>
                <template v-else-if="currentMaterial.type === 'PDF'">
                  <h3>PDF 资料: {{ currentMaterial.name }}</h3>
                  <a :href="currentMaterial.filePath" target="_blank" class="pdf-link">点击下载 PDF</a>
                  <div class="pdf-viewer-container">
                    <template v-if="currentMaterial.filePath">
                      <VuePdfEmbed :source="currentMaterial.filePath" class="vue-pdf-embed" />
                    </template>
                    <el-empty v-else description="PDF 资料路径无效"></el-empty>
                  </div>
                  <div class="comments-section">
                    <h3>评论区</h3>
                    <div class="comment-input-area">
                      <el-input
                        v-model="newCommentContent"
                        :placeholder="replyingToUserName ? `回复 ${replyingToUserName}:` : '发表评论...'"
                        type="textarea"
                        :rows="3"
                        clearable
                      ></el-input>
                      <div class="comment-submit-actions">
                        <el-button v-if="replyingToCommentId" type="text" @click="replyingToCommentId = null; replyingToUserName = ''; newCommentContent = '';">取消回复</el-button>
                        <el-button type="primary" @click="submitComment">提交评论</el-button>
                      </div>
                    </div>

                    <el-divider v-if="comments.length > 0">评论列表</el-divider>

                    <div v-if="comments.length > 0" class="comment-list-container">
                      <CommentItem
                        v-for="comment in comments"
                        :key="comment.commentID"
                        :comment="comment"
                        @reply="handleReply"
                      />
                    </div>
                    <el-empty v-else description="暂无评论"></el-empty>
                  </div>
                </template>
                <template v-else-if="currentMaterial.type === 'IMAGE'">
                  <h3>图片资料: {{ currentMaterial.name }}</h3>
                  <img :src="currentMaterial.filePath" alt="资料图片" class="material-image" />
                </template>
                <template v-else>
                  <h3>其他资料: {{ currentMaterial.name || '未命名资料' }}</h3>
                  <a :href="currentMaterial.filePath" target="_blank">点击下载资料</a>
                </template>
              </div>
            </div>
          </el-col>

          <el-col :span="6">
            <div class="chapter-tree-area">
              <h3>目录</h3>
              <el-empty v-if="chapters.length === 0" description="暂无目录"></el-empty>
              <el-tree
                :data="chapters"
                :props="chapterProps"
                node-key="id"
                default-expand-all
                @node-click="handleChapterClick"
                :current-node-key="currentChapterId"
                highlight-current
              >
              </el-tree>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getCourseChapters, getChapterMaterials, getChapterComments } from '../api/course'
import { postComment } from '../api/user'
import { ElMessage } from 'element-plus'
import request from '../utils/request'
import { Back } from '@element-plus/icons-vue'
import VuePdfEmbed from 'vue-pdf-embed'
import CommentItem from '../components/CommentItem.vue'

const route = useRoute()
const router = useRouter()
const courseId = ref(null)
const currentChapterId = ref(null)
const currentMaterialId = ref(null)
const currentChapterName = ref('加载中...')
const chapters = ref([]) // 存储课程章节
const loading = ref(false)
const currentMaterial = ref(null) // 存储当前要显示的资料

const comments = ref([]) // 存储评论列表
const newCommentContent = ref('') // 新评论内容
const replyingToCommentId = ref(null) // 回复的评论ID
const replyingToUserName = ref('') // 回复的用户名

const chapterProps = {
  label: 'name',
  children: 'children'
}

// 获取课程章节（右侧目录树）并尝试获取资料类型
const fetchCourseChapters = async () => {
  try {
    const res = await getCourseChapters(courseId.value)
    if (res.code === 1) {
      let fetchedChapters = res.data.chapters || []

      // 递归函数，用于遍历章节树并获取资料信息
      const processChapters = async (chaptersToProcess) => {
        for (const chapter of chaptersToProcess) {
          // Assign a unique ID for the chapter node
          chapter.id = `chapter-${chapter.chapterID}`; // Ensure unique ID for chapters

          if (chapter.children && chapter.children.length > 0) {
            // 如果是父章节，递归处理其子章节
            await processChapters(chapter.children)
          } else {
            // 如果是叶子章节，获取其资料并作为子节点添加
            try {
              const materialRes = await getChapterMaterials(chapter.chapterID)
              if (materialRes.code === 1 && materialRes.data && materialRes.data.materials && materialRes.data.materials.length > 0) {
                chapter.children = chapter.children || []; // Ensure children array exists
                materialRes.data.materials.forEach(material => {
                  let materialLabel = chapter.name; // Use chapter name as the base label
                  if (material.type === 'VIDEO') {
                    materialLabel += ' [视频]';
                  } else if (material.type === 'PDF') {
                    materialLabel += ' [PDF]';
                  }
                  chapter.children.push({
                    id: `material-${material.materialID}`, // Unique ID for material node
                    materialID: material.materialID,
                    chapterID: chapter.chapterID, // Store parent chapterID for navigation/highlighting
                    name: materialLabel, // Displayed name
                    type: material.type,
                    filePath: material.filePath,
                    isMaterial: true // Flag to identify material nodes
                  });
                });
              }
            } catch (error) {
              console.warn(`获取章节 ${chapter.name} 资料失败:`, error);
            }
          }
        }
      }
      await processChapters(fetchedChapters); // 开始处理章节树
      chapters.value = fetchedChapters;

      // 尝试找到当前章节的名称
      findChapterName(chapters.value, currentChapterId.value);

    } else {
      ElMessage.error(res.message || '获取课程章节失败')
      chapters.value = []
    }
  } catch (error) {
    console.error('Failed to fetch course chapters:', error)
    ElMessage.error(error.message || '获取课程章节失败，请重试')
    chapters.value = []
  } finally {
    // Ensure we attempt to fetch material after chapters are loaded
    if (courseId.value && currentChapterId.value) {
      fetchAndSetMaterial(currentChapterId.value, currentMaterialId.value);
    }
  }
}

// 递归查找章节名称并设置当前章节信息
const findChapterName = (chapterList, id) => {
  for (const chapter of chapterList) {
    if (chapter.chapterID === id) {
      currentChapterName.value = chapter.name;
      return chapter.name; // Return the found chapter name
    }
    if (chapter.children) {
      const found = findChapterName(chapter.children, id);
      if (found) {
        return found;
      }
    }
  }
  return null;
};

// 获取并设置要显示的具体资料
const fetchAndSetMaterial = async (chapterID, materialID) => {
  loading.value = true;
  currentMaterial.value = null; // 清空当前资料
  try {
    const res = await getChapterMaterials(chapterID);
    if (res.code === 1 && res.data && res.data.materials && res.data.materials.length > 0) {
      let materialToDisplay = null;
      if (materialID) {
        // 如果指定了 materialID，则查找该资料
        materialToDisplay = res.data.materials.find(m => m.materialID === parseInt(materialID));
      } else {
        // 如果没有指定 materialID，默认显示第一个视频或PDF
        materialToDisplay = res.data.materials.find(m => m.type === 'VIDEO') || 
                            res.data.materials.find(m => m.type === 'PDF') || 
                            res.data.materials[0]; // 否则显示第一个资料
      }
      
      if (materialToDisplay) {
        const parentChapterName = findChapterName(chapters.value, chapterID); // Get the parent chapter name
        let displayMaterialName = parentChapterName || '未命名章节';

        if (materialToDisplay.type === 'VIDEO') {
          displayMaterialName += ' [视频]';
        } else if (materialToDisplay.type === 'PDF') {
          displayMaterialName += ' [PDF]';
          console.log('PDF filePath:', materialToDisplay.filePath); // Log PDF file path
        } else if (materialToDisplay.type === 'IMAGE') {
          displayMaterialName += ' [图片]';
        } else {
          displayMaterialName += ' [其他]';
        }

        currentMaterial.value = { ...materialToDisplay, name: displayMaterialName, chapterID: chapterID }; // 新增 chapterID
        console.log('fetchAndSetMaterial: currentMaterial set to', currentMaterial.value);
      }

      if (currentMaterial.value && currentMaterial.value.type === 'VIDEO') {
        // 视频资料加载后，自动记录观看历史
        watchVideo(currentMaterial.value.materialID);
      }

    } else {
      ElMessage.info('当前章节暂无资料或资料加载失败。');
    }
  } catch (error) {
    console.error('Failed to fetch material:', error);
    ElMessage.error('资料加载失败，请重试。\n' + error.message);
  } finally {
    loading.value = false;
  }
};

// 处理章节目录点击事件
const handleChapterClick = (data, node) => {
  if (data.isMaterial) {
    // 如果点击的是资料节点，直接加载资料
    currentChapterId.value = data.chapterID; // 确保高亮父章节
    currentMaterialId.value = data.materialID; // 更新当前资料ID
    fetchAndSetMaterial(data.chapterID, data.materialID);
    currentChapterName.value = node.parent ? node.parent.label : data.name; // 标题显示父章节名
  } else if (data.children && data.children.length > 0) {
    // 如果是父章节，只展开/收起，不处理资料加载
    return;
  } else {
    // 如果是叶子章节（没有资料作为子节点），则默认加载该章节的第一个资料
    // 或者跳转到 MaterialViewer 页面，让其显示 "暂无资料"
    router.push({
      name: 'materialViewer',
      params: {
        courseId: courseId.value,
        chapterId: data.chapterID,
        // 不传入 materialId，让 fetchAndSetMaterial 决定默认显示哪个
      },
    });
  }
};

// 记录观看历史
const watchVideo = async (materialID) => {
  if (!materialID) return
  try {
    const res = await request({
      url: `/course/watch/${materialID}`,
      method: 'get'
    })
    if (res.code === 1) {
      console.log('观看历史记录成功')
    } else {
      console.warn(res.message || '观看历史记录失败')
    }
  } catch (error) {
    console.error('Failed to record watch history:', error)
  }
}

// 提交评论
const submitComment = async () => {
  console.log('submitComment: currentMaterial.value', currentMaterial.value);
  if (!newCommentContent.value.trim()) {
    ElMessage.warning('评论内容不能为空！')
    return
  }

  // 评论是针对章节的，使用当前资料所属的章节ID
  const chapterIDToComment = currentMaterial.value ? currentMaterial.value.chapterID : null;

  if (!chapterIDToComment) {
    ElMessage.error('无法确定评论所属的章节，请先选择一个资料。');
    return;
  }

  try {
    const res = await postComment({
      content: newCommentContent.value,
      chapterID: chapterIDToComment,
      parentCommentID: replyingToCommentId.value
    })
    if (res.code === 1) {
      ElMessage.success('评论发表成功！')
      newCommentContent.value = ''
      replyingToCommentId.value = null
      replyingToUserName.value = ''
      fetchComments(chapterIDToComment) // 刷新评论列表
    } else {
      ElMessage.error(res.message || '评论发表失败！')
    }
  } catch (error) {
    console.error('Failed to post comment:', error)
    ElMessage.error(error.message || '评论发表失败，请重试！')
  }
}

// 处理回复点击事件
const handleReply = (commentId, userName) => {
  replyingToCommentId.value = commentId
  replyingToUserName.value = userName
  newCommentContent.value = `@${userName} `
}

// 格式化评论列表为树形结构（与CourseDetail.vue中相同）
const formatCommentsAsTree = (commentList) => {
  const commentMap = {};
  commentList.forEach(comment => {
    commentMap[comment.commentID] = { ...comment, children: [] };
  });

  const rootComments = [];
  commentList.forEach(comment => {
    if (comment.parentCommentID === null || !commentMap[comment.parentCommentID]) {
      // 顶级评论或父评论不存在，视为顶级评论
      rootComments.push(commentMap[comment.commentID]);
    } else {
      // 子评论，添加到父评论的children中
      commentMap[comment.parentCommentID].children.push(commentMap[comment.commentID]);
    }
  });
  return rootComments;
};

// 获取评论列表
const fetchComments = async (chapterIdToFetch) => {
  console.log('fetchComments: attempting to fetch for chapterID', chapterIdToFetch);
  if (!chapterIdToFetch) {
      comments.value = []; // 清空评论，因为没有章节ID
      return;
  }

  loading.value = true;
  try {
    const res = await getChapterComments(chapterIdToFetch);
    if (res.code === 1) {
      comments.value = formatCommentsAsTree(res.data || []);
    } else {
      ElMessage.error(res.message || '获取评论失败');
      comments.value = [];
    }
  } catch (error) {
    console.error('Failed to fetch comments:', error);
    ElMessage.error(error.message || '获取评论失败，请重试');
    comments.value = [];
  } finally {
    loading.value = false;
  }
};

// 监听 currentMaterial 的变化，当资料改变时加载对应章节的评论
watch(currentMaterial, (newMaterial) => {
  console.log('watch(currentMaterial) triggered. newMaterial:', newMaterial);
  if (newMaterial && newMaterial.chapterID) {
    fetchComments(newMaterial.chapterID);
  } else {
    comments.value = []; // 没有当前资料或章节ID时清空评论
  }
}, { immediate: true }); // immediate: true 确保组件加载时立即执行一次

const goBack = () => {
  router.push(`/course/${courseId.value}`)
}

onMounted(() => {
  courseId.value = route.params.courseId
  currentChapterId.value = parseInt(route.params.chapterId) // 确保是数字
  currentMaterialId.value = route.params.materialId ? parseInt(route.params.materialId) : null; // 获取可选的 materialId

  if (courseId.value) {
    fetchCourseChapters()
  }

  // 不需要在这里额外调用 fetchAndSetMaterial，因为它会在 fetchCourseChapters 的 finally 块中被触发
  // 或者，如果章节树加载完毕后，确保当前资料被正确设置，会通过 watch(currentMaterial) 触发 fetchComments
})

// 监听路由参数变化，以便在URL变化时重新加载资料
watch(() => route.params, (newParams, oldParams) => {
  const newCourseId = newParams.courseId;
  const newChapterId = parseInt(newParams.chapterId);
  const newMaterialId = newParams.materialId ? parseInt(newParams.materialId) : null;

  // 仅当 courseId 或 chapterId 发生变化时才重新获取章节列表和资料
  if (newCourseId !== courseId.value || newChapterId !== currentChapterId.value) {
    courseId.value = newCourseId;
    currentChapterId.value = newChapterId;
    currentMaterialId.value = newMaterialId;
    fetchCourseChapters(); // 重新获取章节列表以更新高亮状态和资料标识
    fetchAndSetMaterial(newChapterId, newMaterialId); // 获取并设置新章节的资料
  } else if (newMaterialId !== currentMaterialId.value) {
    // 如果只有 materialId 变化，则只更新显示的资料
    currentMaterialId.value = newMaterialId;
    fetchAndSetMaterial(currentChapterId.value, newMaterialId); // 仅更新当前章节的资料
  }
}, { deep: true }); // 深度监听路由参数的变化

</script>

<style scoped>
.material-viewer-page {
  width: 95vw;
  padding: 20px;
  min-height: calc(100vh - 80px); /* 减去顶部导航和底部 */
  background-color: #f0f2f5;
}

.viewer-card {
  max-width: 100vw;
  margin: 0 auto;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.card-header .el-button {
  margin-right: 15px;
}

.chapter-title {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.materials-container {
  padding: 20px 0;
}

.material-display-area {
  padding-right: 20px;
}

.chapter-tree-area {
  padding-left: 20px;
}

.material-item {
  margin-bottom: 30px;
  background-color: #ffffff;
  padding: 20px;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.material-item h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 20px;
  color: #303133;
}

.material-video, .material-image {
  width: 100%;
  height: auto;
  background-color: #000;
  border-radius: 4px;
  display: block; /* 确保图片或视频是块级元素 */
  margin-bottom: 10px;
}

.pdf-link {
  display: inline-block;
  margin-bottom: 10px;
  font-size: 16px;
  color: #409EFF;
  text-decoration: underline;
}

iframe {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
}

/* Custom tree node styles are removed as they are not needed for nested rendering */
/*
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.material-tag {
  margin-left: 10px;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
}

.video-tag {
  background-color: #e6f7ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.pdf-tag {
  background-color: #fff0f6;
  color: #eb2f96;
  border: 1px solid #ffadd2;
}
*/

.material-image {
  max-width: 100%;
  height: auto;
  display: block;
}

.pdf-viewer-container {
  width: 100%;
  height: 800px; /* Adjust height as needed */
  border: 1px solid #eee;
  overflow: auto; /* Enable scrolling for large PDFs */
}

.vue-pdf-embed {
  width: 100%;
  height: 100%;
}

/* New styles for comments section */
.comments-section {
  margin-top: 30px;
  padding: 20px;
  background-color: #f8f8f8;
  border-radius: 4px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.03);
}

.comments-section h3 {
  margin-bottom: 20px;
  font-size: 20px;
  color: #303133;
  text-align: center;
}

.comment-input-area {
  margin-bottom: 20px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  padding: 15px;
  background-color: #fff;
}

.comment-input-area .el-textarea {
  margin-bottom: 10px;
}

.comment-submit-actions {
  text-align: right;
}

.comment-list-container {
  margin-top: 20px;
}

.el-divider {
  margin: 30px 0;
}
</style>